let timer = null;

chrome.runtime.sendMessage({
	type: "checkFlag"
}, (response) => {
	if (response && response.hasOwnProperty("runtime")) {
		if (response.runtime) {
			getDelayTime();
		}
	}
});

function getDelayTime() {
	if (timer) {
		clearInterval(timer);
	}
	chrome.storage.sync.get("goodsList", function(result) {
		let goodsList = result.goodsList || [];
		let delayTime = 3000;
		if (goodsList) {
			delayTime = goodsList.length * 5000 + 3000;
		}
		timer = setInterval(() => build(), delayTime);
	});
}

function build() {
	// 从Google插件中获取商品列表
	chrome.storage.sync.get("goodsList", function(result) {
		let goodsList = result.goodsList || [];
		// 遍历商品列表，创建表格行
		let delayTime = 2000;
		for (let i = 0; i < goodsList.length; i++) {
			let goods = goodsList[i];
			let clear = false;
			if (i == goodsList.length - 1) {
				clear = true;
			}
			setTimeout(() => request(goods.id, goods.minPrice, goods.maxPrice, goods.minPaintwear, goods
				.maxPaintwear, clear), delayTime)
			delayTime = delayTime + 5000;
		}
	});
}

let baseUrl = 'https://buff.163.com/api/market/goods/sell_order';
let visitBaseUrl = 'https://buff.163.com/goods/';

function request(goodsId, minPrice, maxPrice, minPaintwear, maxPaintwear, clear) {
	console.log("获取信息开始，商品id:" + goodsId + "，请求时间:" + new Date().toLocaleString());
	let queryParams = new URLSearchParams();
	queryParams.append('game', 'csgo');
	queryParams.append('goods_id', goodsId);
	queryParams.append('page_num', '1');
	queryParams.append('page_size', '50');
	queryParams.append('sort_by', 'default');
	queryParams.append('allow_tradable_cooldown', '1');
	queryParams.append('min_price', minPrice);
	queryParams.append('max_price', maxPrice);
	queryParams.append('min_paintwear', minPaintwear);
	queryParams.append('max_paintwear', maxPaintwear);
	queryParams.append('_', Date.now());
	var url = `${baseUrl}?${queryParams.toString()}`;

	if (clear == true) {
		getDelayTime();
	}

	httpGet(url, function(res) {
		if (res.code != "OK") {
			console.log("获取商品失败", res)
			return
		}
		let data = res.data
		let items = data.items
		if (items.length < 1) {
			console.log("%c查询不到该类型的商品", 'color: #F56C6C');
			return;
		}
		let goodsName = data.goods_infos[goodsId].name
		for (let i = 0; i < items.length; i++) {
			let item = items[i]
			let price = item.price
			let asset_info = item.asset_info
			let paintwear = asset_info.paintwear
			maxPrice = Number(price);
			minPaintwear = Number(paintwear.substr(0, 6));
			minPrice = maxPrice - Number('0.01');
			maxPaintwear = minPaintwear + Number('0.0001');
			let visitParams = new URLSearchParams();
			visitParams.append('page_num', '1');
			visitParams.append('min_price', minPrice.toFixed(2));
			visitParams.append('max_price', maxPrice);
			visitParams.append('min_paintwear', minPaintwear);
			visitParams.append('max_paintwear', maxPaintwear.toFixed(4));
			let visitUrl = `${visitBaseUrl}${goodsId}#${visitParams.toString()}`;
			let log = `商品名称:${goodsName},商品价格:${price},磨损:${paintwear}, 购买链接:${visitUrl}`;
			console.log("%c" + log, 'color: #67C23A');
		}

	});
}


function httpGet(url, callback) {
	var xhr = new XMLHttpRequest();
	xhr.withCredentials = true;
	xhr.open("GET", url, true);
	xhr.setRequestHeader("Accept", "*/*");
	xhr.onreadystatechange = function() {
		if (xhr.readyState === 4 && xhr.status === 200) {
			callback(JSON.parse(xhr.responseText));
		}
	};
	xhr.send();
}